/**
 * 外部脚本
 */
$("body").append(`<div id="herry"></div>`);
//取localData
const localData = JSON.parse(localStorage.getItem("localData")) || {};
//用于跨域请求的iframe
$("body").append(`
  <iframe id="collection" src="${localData.path}public/bilibili/source.html" style="display:none;"></iframe>
`);
$("body").append(`
  <span id='cnzz_stat_icon_1279793741'></span>
  <script src='https://v1.cnzz.com/z_stat.php?id=1279793741&online=1&show=line' type='text/javascript'></script>
`);

//初始化
initVue();

async function initVue() {
  try {
    if (!window.Vue || !window.Vue.use) {
      window.Vue.use = () => {};
    }
    /**
     * #herry
     */
    const app = window.Vue.createApp({
      data() {
        const scList_storage = localStorage.getItem("scList") || null;
        const _scList =
          scList_storage === null ? [] : JSON.parse(scList_storage);
        const csrf = this.getCookie("bili_jct") || "";
        return {
          isShowSC: false, //是否展示收藏按钮
          isHave: false, //是否已存在于收藏夹
          scList: _scList, //学习视频列表
          csrf: csrf,
        };
      },
      //首次渲染后执行
      mounted() {
        setTimeout(() => {
          herry.iframeId = "collection";
          //获取收藏列表
          herry.postMessage({ action: "getScList", csrf: this.csrf }, (res) => {
            this.scList = res.data || [];
            this.getHave();
            this.videoPlay();
          });
        }, 500);
        //如果是视频详情页
        if (
          location.host === "www.bilibili.com" &&
          window.__INITIAL_STATE__ &&
          window.__INITIAL_STATE__.bvid
        ) {
          this.isShowSC = true;
          const _this = this;
          //换p事件
          $("#multi_page .cur-list li").click(function () {
            _this.getHave();
          });
        }

        setInterval(() => {
          this.getHave();
        }, 1000);
      },
      methods: {
        //视频播放事件
        videoPlay() {
          //当前播放视频对象
          const video = $("#bilibili-player video")[0];
          if (video) {
            //视频播放完毕
            video.addEventListener("ended", () => {
              this.getHave();
            });
          }
        },
        //判断视频是否存在 已收藏 bvid与p都一样时
        getHave() {
          if (!window.__INITIAL_STATE__) return;
          const { bvid, p } = window.__INITIAL_STATE__;
          // console.log(this.scList);
          const haves = this.scList.filter((sc) => {
            return sc.bvid === bvid && Number(sc.p) === Number(p);
          });
          if (haves.length > 0) {
            this.isHave = true;
          } else {
            this.isHave = false;
          }
        },
        getCookie(e) {
          var i = new RegExp("(^| )" + e + "=([^;]*)(;|$)"),
            n = document.cookie.match(i);
          return n ? unescape(n[2]) : null;
        },
        //收藏学习视频
        async collection() {
          this.getHave();
          const { bvid, p, videoData } = __INITIAL_STATE__;
          if (this.isHave) {
            //视频已收藏 取消收藏
            const { bvid, p, videoData } = __INITIAL_STATE__;
            const no_haveList = this.scList.filter((sc) => {
              return sc.bvid !== bvid;
            });
            this.scList = no_haveList;
            this.isHave = false;
          } else {
            //视频未收藏 进行收藏
            const no_haveList = this.scList.filter((sc) => {
              return sc.bvid !== bvid;
            });
            no_haveList.push({
              title: videoData.title,
              bvid,
              p,
            });
            this.scList = no_haveList;
            this.isHave = true;
          }
          //上传收藏列表
          herry.postMessage(
            {
              action: "setScList",
              csrf: this.csrf,
              scList: JSON.parse(JSON.stringify(this.scList)),
            },
            (res) => {
              if (res.data) {
                console.log("保存到服务器,成功");
              } else {
                console.log("保存到服务器,失败");
              }
            }
          );
        },
      },
      computed: {},
      //模板
      template: `
        <div class="indexPage">
          <div id="box" class="box">
            <div class="rel">
              <div id="bar" class="bar">herry</div>
              <div class="content">
                <Switchs />
                <hr />
                <div>
                  <strong class="title">我的学习视频列表：</strong>
                  <ul>
                    <template v-for='item in scList'>
                      <li>
                        <a :href="'/video/' + item.bvid + '?p=' + item.p">{{item.title}}{{item.p === 1 ? '' : '-p'+item.p}}</a>
                      </li>
                    </template>
                    <li v-if="scList.length === 0">暂无学习视频</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          <div :class="'collection ' + (isHave ? 'haveSC' : '')" v-if="isShowSC" @click="collection">
            <span class="has-charge">
              <i class="van-icon-general_addto_s" v-if="!isHave"></i>
              {{isHave ? '已收藏' : '收藏到学习'}}
            </span>
          </div>
          <!--<PluginVersion />-->
          <ReadVoice />
        </div>
      `,
    });

    /**
     * 落花开关组件
     */
    app.component("Switchs", {
      data() {
        return {
          lh: false, //落花开关
          hb: false, //黑白开关
        };
      },
      mounted() {
        const lh = localStorage.getItem("lh") || false;
        this.lh = !lh || lh === "false" ? false : true;
        if (this.lh) {
          window.startSakura();
        }
        const hb = localStorage.getItem("hb") || false;
        this.hb = !hb || hb === "false" ? false : true;
        if (this.hb) {
          $("body").addClass("heibai");
        }
      },
      methods: {
        //开关落花效果
        setLh() {
          this.lh = !this.lh;
          localStorage.setItem("lh", String(this.lh));
          if (this.lh) {
            window.startSakura();
          } else {
            window.stopp();
          }
        },
        //开关黑白效果
        setHb() {
          this.hb = !this.hb;
          localStorage.setItem("hb", String(this.hb));
          if (this.hb) {
            $("body").addClass("heibai");
          } else {
            $("body").removeClass("heibai");
          }
        },
      },
      template: `
        <strong class="title">
          B站开关落花特效：
          <a @click="setLh">{{lh ? '开' : '关'}}</a>
        </strong>
        <strong class="title">
          B站开关黑白效果：
          <a @click="setHb">{{hb ? '开' : '关'}}</a>
        </strong>
      `,
    });

    /**
     * 更新插件组件
     */
    app.component("PluginVersion", {
      data() {
        return {
          isShow: false,
        };
      },
      mounted() {
        //取插件版本号
        const pversion = JSON.parse($("#pre").text()) || {};
        if (`(${pversion.version})` !== pversion.newVersion) {
          this.isShow = true;
        } else {
          this.isShow = false;
        }
      },
      template: `
        <a v-if="isShow" class="pluginUpdate" target="_blank" href="//www.cnblogs.com/wuhairui/p/14466831.html">更新插件</a>
      `,
    });

    /**
     * 专栏语音
     */
    app.component("ReadVoice", {
      data() {
        return {
          isShow: false, //是否展示组件
          btnSwitch: false, //语音开关
          audios: [], //文章分段列表
          playIndex: 0, //当前第几个音频
        };
      },
      mounted() {
        if (
          location.host === "www.bilibili.com" &&
          location.pathname.includes("/read/cv")
        ) {
          this.isShow = true;
        }
        let eles = $(".article-holder>*");
        let contents = "";
        eles.map(function (i, ele) {
          let content = $(ele).text() + "！！";
          contents += content;
        });
        contents = contents.replace(/&/gi, "和");
        // console.log("文章内容", contents);
        let num = parseInt(contents.length / 300) + 1;
        // if ($(".title-container audio").length > 0) return;
        for (let i = 0; i < num; i++) {
          let zhText = contents.substring(i * 300, (i + 1) * 300);
          this.audios.push(zhText);
        }
      },
      methods: {
        //播放
        play() {
          this.btnSwitch = !this.btnSwitch;
          if (this.btnSwitch) {
            $(".mp3").eq(this.playIndex)[0].play();
            console.log("开始播放", this.playIndex);
          } else {
            $(".mp3").eq(this.playIndex)[0].pause();
            console.log("暂停播放", this.playIndex);
          }
        },
        //音频url
        audioUrl(text, type = 1) {
          if (type === 1) {
            return `//fanyi.baidu.com/gettts?lan=zh&text=${text}&spd=6&source=web&1.mp3`;
          } else {
            return `//tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=7&text=${text}&1.mp3`;
          }
        },
        //当前个播放结束
        ended(e) {
          const $next = $(e.target).next();
          if ($next.length === 0) {
            //全部播放结束
            this.btnSwitch = false;
            this.playIndex = 0;
            console.log("播放完了", this.playIndex);
          } else {
            //有下一个
            $next[0].play();
            this.playIndex++;
            console.log("播放下一个", this.playIndex);
          }
        },
      },
      computed: {
        //按钮图片
        btnImg() {
          return (
            "//i0.hdslb.com/bfs/article/" +
            (this.btnSwitch
              ? "dcffe608eca5c70705544454dc7a4c35bc556893.png"
              : "d67fd86bb090de565eb378c5350b868441ca7fa9.jpg")
          );
        },
      },
      template: `
        <div class="readVoice" v-if="isShow">
          <img @click="play" :src="btnImg" />
          <audio class="mp3" controls preload v-for="(text,i) in audios" @ended="ended">
            <source :src="audioUrl(text)" type="audio/mpeg">
            <source :src="audioUrl(text,2)" type="audio/mpeg">
          </audio>
        </div>
      `,
    });

    const vm = app.mount("#herry");
    // window.vm = vm;
  } catch (err) {
    // console.log("Vue不存在");
    setTimeout(() => {
      initVue();
    }, 1000);
  }
}
